import router from './router'
import store from './store'
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'
import { getToken, removeKeys, removeAllKeys, getRoles } from './utils/cookies.js'
// NProgress.configure({ showSpinner: false })
const whiteList = ['login']
router.beforeEach(async (to, from, next) => {
	// NProgress.start()
	var hasToken = getToken()
	if (hasToken) {
		if (to.path === '/login') {
			next({ path: '/' })
			// NProgress.done()
		} else {
			if (store.state.user.role.length==0) {
				store.dispatch('user/getRole').then((role) => {
					if(role.length==0){
						removeAllKeys()
						console.log('获取权限失效，请重新登录')
						next({name:'login'})
					}else{
						store.dispatch('router/getRoutes', role).then((routes) => {
							// console.log('aaa',store.state.router.sidebar)
							routes.forEach(route => {
								router.addRoute(route)
							})
							const redirect = decodeURIComponent(from.query.redirect || to.path)
							if (to.path === redirect) {
								next({ ...to, replace: true })
							} else {
								next({ path: redirect })
							}
						})
					}
				})
			} else {
				next()
			}
		}
	} else {		
		removeAllKeys()
		if (whiteList.includes(to.name)) {
			next()
			// NProgress.done()
		} else {
			next({name:'login'})
			// NProgress.done()
		}
	}
})
router.afterEach((to, from) => {
	document.title = to.meta.title
	// NProgress.done()
})
